package com.itheima.reggie_auto.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie_auto.dto.DishDto;
import com.itheima.reggie_auto.dto.SetmealDto;
import com.itheima.reggie_auto.entity.Dish;
import com.itheima.reggie_auto.entity.DishFlavor;
import com.itheima.reggie_auto.entity.SetmealDish;
import com.itheima.reggie_auto.exception.CustomException;
import com.itheima.reggie_auto.mapper.DishMapper;
import com.itheima.reggie_auto.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void save(DishDto dishDto) {
        //分析  涉及 两张表  第一张dish  和口味 flavor表

        //添加到dish表 --  sql
        dishMapper.insertDish(dishDto);

        //添加到口味表  -- 需要设置进去dish_id
        List<DishFlavor> flavors = dishDto.getFlavors();
        //设置dish_id
        flavors = flavors.stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);



    }

    /*  @Override
      public Page<DishDto> page(int page, int pageSize, Dish dish) {
          //定义dish 表的page对象  还需要定义一个dishdto的page对象  中间穿插数据的对拷
          // 因为页面需要显示种类名称 需要从category表中查询
          //查询出来再设置进dishdto的page对象的records中再返回

          Page<Dish> dishPage = new Page<>(page, pageSize);
          Page<DishDto> dtoPage = new Page<>();

          LambdaQueryWrapper<Dish> dishlqw = new LambdaQueryWrapper<>();
          dishlqw.orderByDesc(Dish::getUpdateTime);
          //模糊查询
          dishlqw.like(dish.getName() != null, Dish::getName, dish.getName());
          //查询
          dishMapper.selectPage(dishPage, dishlqw);

          //数据对拷
          BeanUtils.copyProperties(dishPage, dtoPage, "records");

          //将菜品种类名称设置进records
          List<Dish> records = dishPage.getRecords();
          List<DishDto> collect = records.stream().map(item -> {
              DishDto dishDto = new DishDto();

              //数据对拷
              BeanUtils.copyProperties(item, dishDto);

              Long categoryId = item.getCategoryId();
              Category category = categoryService.getById(categoryId);
              //非空判断
              if (category != null && category.getName() != null) {
                  dishDto.setCategoryName(category.getName());
              }
              return dishDto;
          }).collect(Collectors.toList());

          ///设置dtoPage中
          dtoPage.setRecords(collect);

          return dtoPage;
      }*/

    //sql
    public Page<DishDto> page(int page, int pageSize, Dish dish) {
        Page<DishDto> pageInfo = new Page<>(page, pageSize);
        if (dish.getName() != null && dish.getName() != "") {
            dish.setName("%" + dish.getName() + "%");
        }
        // long total = dishMapper.selectCount(dish.getName());
        dishMapper.selectByPage(pageInfo, dish.getName());
        // pageInfo.setTotal(total);
        return pageInfo;
    }

        @Override
        public DishDto getById(Long id) {

            //1.需要查询 菜品表
            Dish dish = dishMapper.selectById(id);
            DishDto dishDto = new DishDto();
            //数据对拷
            BeanUtils.copyProperties(dish, dishDto);
            //2.根据dish_id查询口味表
            List<DishFlavor> flavorList = dishFlavorService.getByDishId(id);
            dishDto.setFlavors(flavorList);
            return dishDto;
        }


    @Override
    public void update(DishDto dishDto) {
        //分析 本次更新涉及两张表，一张dish表，一张口味表

        //dish表直接更新即可
        dishMapper.updateById(dishDto);

        //口味表需要先清空 在新增  ， 并且把dish_id 字段赋上值
        dishFlavorService.deleteByDishId(dishDto.getId());

        List<DishFlavor> flavors = dishDto.getFlavors().stream().map(item -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void updateByIds(Integer status, Long[] ids) {
        //分析  批量修改即可。遍历修改

        Dish dish = new Dish();
        for (Long id : ids) {
            dish.setStatus(status);
            dish.setId(id);
            dishMapper.updateById(dish);
        }

    }

    @Override
    public void deleteByIds(List<Long> ids) {
        //分析：菜品起售状态不能删，套餐里有 不能删
        // 根据id查，状态为1的数量
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getStatus,1);
        lqw.in(Dish::getId,ids);
        List<Dish> dishes = dishMapper.selectList(lqw);
        if (dishes!=null&&dishes.size()>0) {
            throw new CustomException("起售状态不能被删除");
        }
        //根据菜品id查套餐菜品关系表是否有值
        for (Long id : ids) {
          SetmealDish setmealDish = setmealDishService.getByDishId(id);
            if (setmealDish != null) {
                SetmealDto setmeal = setmealService.getById(setmealDish.getSetmealId());
                throw new CustomException(setmeal.getName()+"套餐中有"+setmealDish.getName()+"菜品，不能删除");
            }
        }

       /* Integer dishCount = setmealDishService.getByDishIds(ids);

        if (dishCount > 0) {
            throw new CustomException("套餐中有该菜品，不能删除");
        }*/



        dishMapper.deleteBatchIds(ids);
    }

    @Override
    public List<DishDto> getByCategoryId(Dish dish) {
        List<DishDto> dishDtoList = null;

        //判断缓存中是否有数据，有数据则直接返回数据
        //组成redis中的key
        String key = "dish_"+dish.getCategoryId()+"_1";

        //查询缓存
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null) {
            return dishDtoList;
        }

        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishes = dishMapper.selectList(lqw);

        dishDtoList  = dishes.stream().map(item->{
           DishDto dishDto = new DishDto();

           //数据拷贝
            BeanUtils.copyProperties(item,dishDto);
            //查询口味  设置口味
            List<DishFlavor> dishFlavors = dishFlavorService.getByDishId(item.getId());
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());

        //存到缓存   时间一个小时
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return dishDtoList;
    }
}
